package com.ganzi.ganziserver.rabbit.recevie;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ganzi.ganziserver.dao.ControlLogDao;
import com.ganzi.ganziserver.dao.SchoolInformationDao;
import com.ganzi.ganziserver.rabbit.send.SendUtil;
import com.ganzi.ganziserver.utils.Topic;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;

@Service

public class DeadRecevie {

    private static Logger log = LoggerFactory.getLogger(SendUtil.class);
    @Autowired
    ControlLogDao logdao;

    @Autowired
    SchoolInformationDao schooldao;

    @RabbitListener(queues = Topic.DEAD_ROUTING_KEY)
    public void process(Message message, Channel channel)throws IOException {
        try{
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("死信箱收到消息："+new String(message.getBody()));
            if(message.getBody().length<=0)return;
            JSONObject info = (JSONObject)JSON.parse(message.getBody());
            String type = info.getString("type");
            if("-2".equals(type)){
                return;
            }
            String channelName = info.getString("channelName");
            if(StringUtils.isNotBlank(channelName) && !Topic.SCHOOL_STATE.equals(channelName)){
                schooldao.updateSchoolForOnline(channelName,2);
                String infoid = info.getString("infoId");
                String error = "客户端离线/拒绝";
                logdao.updateControlLogStateByInfoId(2,error,infoid);
            }
        }catch (Exception e){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("死信箱异常："+e.getMessage());
        }
    }
}
